<?php

namespace app\logic;

use app\components\helpers\ArrayHelper;
use app\components\helpers\DropListHelper;
use app\components\helpers\TreeHelper;
use app\models\Department;
use app\models\Group;
use app\models\Item;
use app\models\Position;
use app\models\User;
use yii\helpers\Json;
use yii\web\HttpException;
use app\forms\PositionForm;

/**
 * 岗位逻辑类
 */
class PositionLogic extends BaseLogic
{
    /**
     * 创建岗位
     * @param $param
     * @throws HttpException
     */
    public static function create($param)
    {
        $form = self::_validateForm($param, 'create');
        $attr = $form->getAttributes();
        Position::newCreate($attr);
        throw new HttpException(200, 'OK');
    }

    /**
     * 编辑岗位
     * @param $param
     * @throws HttpException
     */
    public static function update($param)
    {
        $form = self::_validateForm($param, 'update');
        Position::performUpdate($form->getAttributes());
        throw new HttpException(200, 'OK');
    }

    /**
     * 删除岗位
     * @param $param
     * @throws HttpException
     * @throws \Throwable
     */
    public static function delete($param)
    {
        $form = self::_validateForm($param, 'delete');
        $model = Position::findOne($form['id']);
        $childrenCount = $model->getChildrenCount();
        $userCount = $model->getUserCount();
        if ($userCount || $childrenCount) {
            throw new HttpException(423);
        }
        $model->performDelete();
        throw new HttpException(200);
    }

    /**
     * 岗位详情
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function view($param)
    {
        $form = self::_validateForm($param, 'delete');
        $position = Position::getViewById($form['id']);
        $user = User::getListByPositionId($form['id']);
        return ['position' => $position, 'user' => $user];
    }

    /**
     * 岗位下拉列表数据
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getDropList($param)
    {
        $form = self::_validateForm($param, 'get-drop-list');
        return self::_getList($form['groupId'], $form['deptId']);
    }

    /**
     * 岗位编辑的信息
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getInfo($param)
    {
        $form = self::_validateForm($param, 'get-info');
        $column = ['id', 'name', 'parent_id AS parentId', 'group_id AS groupId', 'dept_id AS deptId'];
        $position = Position::getSingleByPk($form['id'], $column); // 当前岗位信息
        $itemArr = Item::getListForAuth(); // 所有权限项
        $ownItemArr = Position::getOwnItemList($form['id']); // 已赋予的权限项
        $item = self::_setItemCheck($itemArr, $ownItemArr); // 合并已赋予的权限项
        $group = GroupLogic::getDropList(); // 组织列表
        $dept = DepartmentLogic::_getList($position['groupId']); // 部门列表
        $list = self::_getList($position['groupId'], $position['deptId']); // 岗位列表
        return [
            'position' => $position,
            'group' => $group,
            'dept' => $dept,
            'item' => $item,
            'list' => $list
        ];
    }

    /**
     * 自定义数据授权项的明细数据
     * @param $param
     * @return array[]
     * @throws HttpException
     */
    public static function getItemData($param)
    {
        $form = self::_validateForm($param, 'get-item-data');
        // 解析得到所有的id
        if ($form['itemData']) {
            $arr = Json::decode($form['itemData']['data']);
            $ids = !empty($arr) ? explode(',', $arr['ids']) : [];
        } else {
            $ids = [];
        }
        $group = GroupLogic::_getTreeForItemData($ids);
        return ['group' => $group];
    }

    /**
     * 岗位默认的权限项
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getDefaultItem($param)
    {
        $form = self::_validateForm($param, 'get-default-item');
        $itemArr = Item::getListForAuth();
        $itemDef = Position::getDefaultItem($form['id']);
        $item = self::_setItemCheck($itemArr, $itemDef);
        return ['item' => $item];
    }

    /**
     * 某组织 ｜ 某部门 下的岗位 树形列表
     * @param $param
     * @return array|array[]
     * @throws HttpException
     */
    public static function getTreeList($param)
    {
        $form = self::_validateForm($param, 'get-tree-list');
        $positionArr = Position::getListByGroupIdOrDeptId($form['groupId'], $form['deptId']);
        if (empty($positionArr)) {
            return ['position' => []];
        }
        $pidArr = array_column($positionArr, 'parentId');
        sort($pidArr);
        return ['position' => TreeHelper::format($positionArr, $pidArr[0])];
    }

    /**
     * 参数、表单数据 验证
     * @param $param
     * @param $scenario
     * @return PositionForm
     * @throws HttpException
     */
    public static function _validateForm($param, $scenario)
    {
        $form = new PositionForm();
        $form->setScenario($scenario);
        $form->setAttributes($param);
        if (!$form->validate()) {
            throw new HttpException(400, $form->getFirstError());
        }
        return $form;
    }

    /**
     * 组织 & 部门 下的岗位列表
     * @param $groupId
     * @param $deptId
     * @return array
     */
    public static function _getList($groupId, $deptId)
    {
        $positionArr = Position::getListByGroupIdAndDeptId($groupId, $deptId);
        return ((new DropListHelper())->format($positionArr));
    }

    public static function _setItemCheck($item, $ownItem)
    {
        if (!empty($ownItem)) {
            foreach ($ownItem as $oi) {
                if (isset($item[$oi['id']])) {
                    $item[$oi['id']]['type'] = $oi['type'];
                    $item[$oi['id']]['checked'] = 1;
                }
            }
        }
        return TreeHelper::format($item);
    }
}